<?php

namespace common\widgets\distpicker;

use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;
use yii\web\AssetBundle;
use yii\helpers\ArrayHelper;

/**
 * DistpickerInput
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class DistpickerInput extends InputWidget {

    public $districtLevel = [
        'province',
        'city',
        'district',
    ];
    public $clientOptions = [];
    private $_assetBundle;
    public $valueType = 'code';
    public $autoselect = 3;
    public $level = 3;

    /**
     * @inheritdoc
     */
    public function init() {
        parent::init();
        $this->defaultOptions();
        $this->registerAssetBundle();
        $this->registerScript();
    }

    /**
     * @inheritdoc
     */
    public function run() {
        if ($this->hasModel()) {
            $this->setValue($this->model, $this->attribute);
        }
        echo Html::tag('div', $this->renderInput(), $this->options);
    }

    /**
     * Register assetBundle
     */
    protected function registerAssetBundle() {
        $this->_assetBundle = DistpickerAsset::register($this->getView());
    }

    /**
     * @return AssetBundle
     */
    public function getAssetBundle() {
        if (!($this->_assetBundle instanceof AssetBundle)) {
            $this->registerAssetBundle();
        }
        return $this->_assetBundle;
    }

    /**
     * @return bool|string The path of assetBundle
     */
    public function getSourcePath() {
        return Yii::getAlias($this->getAssetBundle()->sourcePath);
    }

    /**
     * Sets default options
     */
    protected function defaultOptions() {
        $options = [
            'data-toggle' => 'distpicker',
        ];
        if ($this->valueType) {
            $options['data-value-type'] = $this->valueType;
        }
        if ($this->autoselect) {
            $options['data-autoselect'] = $this->autoselect;
        } else {
            $this->clientOptions['province'] = '- 所在省 -';
            $this->clientOptions['city'] = '- 所在市 -';
            $this->clientOptions['district'] = '- 所在区 -';
        }

        $this->options = ArrayHelper::merge($options, $this->options);
        Html::removeCssClass($this->options, 'form-control');
        Html::addCssClass($this->options, 'form-select-flex');
    }

    /**
     * Render a HTML input tag.
     *
     * This will call [[Html::activeInput()]] if the input widget is [[hasModel()|tied to a model]],
     * or [[Html::input()]] if not.
     *
     * @param string $type the type of the input to create.
     * @return string the HTML of the input field.
     * @since 2.0.13
     * @see Html::activeInput()
     * @see Html::input()
     */
    protected function renderInput() {
        $id = Html::getInputId($this->model, $this->attribute);
        $name = Html::getInputName($this->model, $this->attribute) . '[]';
        $inputElements = [];
        for ($i = 0; $i < $this->level; $i++) {
            $options = [
                'id' => $id . '-' . $i,
                'name' => $name,
                'class' => 'form-control'
            ];
            $_name = 'data-' . $this->districtLevel[$i];
            if (isset($this->value[$i]) && $this->value[$i]) {
                $options[$_name] = $this->value[$i];
            }
            $inputElements[] = Html::tag('select', '', $options);
        }
        $inputElements[] = Html::activeHiddenInput($this->model, $this->attribute . '_hidden', [
            'value' => implode(',', $this->value?:[])
        ]);
        return implode('', $inputElements);
    }

    public function setValue($model, $attribute) {
        $this->value = $model->$attribute;
    }

    /**
     * Register clients script to View
     */
    protected function registerScript() {
        $clientOptions = !empty($this->clientOptions) ? Json::encode($this->clientOptions) : '';
        $this->getView()->registerJs("jQuery('#{$this->options['id']}').distpicker({$clientOptions});");
    }

}
